package qualomelhor.server;
import java.io.IOException;
import javax.servlet.http.*; 
import java.util.Date;
import com.google.appengine.api.datastore.*;
import com.google.appengine.api.datastore.Query;
import javax.cache.*;
import javax.servlet.*;
import java.util.logging.*;
import java.util.Collections;
import qualomelhor.database.Email;

public class SessionCleanupServlet extends HttpServlet {

    private static final long serialVersionUID = 0;
    private Cache cache = null;
    private static final String EXPIRES = "_expires";
    private static final Logger logger = Logger.getLogger(SessionCleanupServlet.class.getName());
    
	@Override
	public void init(ServletConfig config) throws ServletException {
		try {
			final CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
			cache = cacheFactory.createCache(Collections.emptyMap());
		} catch (final CacheException e) {
        	logger.log(Level.SEVERE, "failed to configure cache", e);
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		final long now = new Date().getTime();
		final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		final Query query = new Query("_ah_SESSION");
		
		boolean limpartudo = false;
		boolean enviarEmail = false;

		if (request.getParameter("tudo") != null) {
			limpartudo = true;
		}
		if (request.getParameter("enviar") != null) {
			enviarEmail = true;
		}

		String result = "";
		long count = 0;
		
		// TODO make this a task
		for (final Entity session : datastore.prepare(query).asIterable(FetchOptions.Builder.withLimit(400))) {
			Long expires = (Long)session.getProperty(EXPIRES);
			if (expires < now || limpartudo) {
				final Key key = session.getKey();
				datastore.delete(key);
				final StringBuilder sb = new StringBuilder("Removed session with expiration ").append((new Date(expires)).toString());
				if (cache != null)
					if (cache.containsKey(key.getName())) {
						cache.remove(key.getName());
						sb.append(", also from memcache");
					}
				logger.log(Level.INFO, sb.toString());
				result += "<BR>" + sb.toString();
				count++;
			}
		}
		
		if (enviarEmail) {
			DAO d = new DAO();
			d.gravaNovoEmail(new Email(new String[]{"o.que.e.melhor@gmail.com"}, "QUAL O MELHOR - Sessao foi Limpa", "", "text/plain", new Date()));
		}

		response.getWriter().write("Total limpo = " + count);
		response.getWriter().write("Resultado = " + result);
    }
}